/*
 * Copyright 2012 Sedov Eduard.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.es.registry;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 *
 * @author Sedov Eduard
 */
public class Node {

    protected String name;
    protected Node parent;
    protected Map<String, Object> values;
    protected List<NodeListener> listeners;

    public Node() {
        this("");
    }

    public Node(String name) {
        this(name, null);
    }

    public Node(String name, Node parent) {
        checkName(name);
        changeName(name);
        changeParent(parent);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        checkName(name);
        changeName(name);
    }

    public Node getParent() {
        return parent;
    }

    public void setParent(Node parent) {
        changeParent(parent);
    }

    public <T> T get(String name) {
        checkName(name);
        return (T) (values == null ? null : values.get(name));
    }

    public <T> T set(String name, Object value) {
        checkName(name);
        return (T) changeValue(name, value);
    }

    public boolean isSet(String name) {
        checkName(name);
        return values == null ? false : values.containsKey(name);
    }

    public Set<String> list() {
        return values == null ? Collections.EMPTY_SET : Collections.unmodifiableSet(values.keySet());
    }

    public <T> T remove(String name) {
        checkName(name);
        T oldValue = (T) changeValue(name, null);
        if (values != null) {
            values.remove(checkName(name));
        }
        fireOnRemove(this, name, oldValue, false);
        return oldValue;
    }

    public void addListener(NodeListener listener) {
        if (listener != null) {
            if (listeners == null) {
                listeners = new ArrayList();
            }
            if (listener != null && !listeners.contains(listener)) {
                listeners.add(listener);
            }
        }
    }

    public void removeListener(NodeListener listener) {
        if (listeners == null) {
            return;
        }
        listeners.remove(listener);
    }

    public List<NodeListener> getListeners() {
        if (listeners == null) {
            return Collections.EMPTY_LIST;
        }
        return new ArrayList(listeners);
    }

    @Override
    public String toString() {
        return getName();
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 53 * hash + (this.name != null ? this.name.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Node other = (Node) obj;
        if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
            return false;
        }
        return true;
    }

    private void changeName(String newName) {
        String oldName = name;
        Node parentNode = getParent();
        if (parentNode != null) {
            parentNode.values.remove(oldName);
            parentNode.values.put(newName, this);
        }
        name = newName;
        fireOnName(this, oldName, newName, false);
    }

    private void changeParent(Node newParent) {
        Node oldParent = parent;
        if (oldParent != null) {
            oldParent.remove(getName());
        }
        if (newParent != null) {
            newParent.set(getName(), this);
        }
        parent = newParent;
        fireOnParent(this, oldParent, newParent, false);
    }

    private <T> T changeValue(String name, Object value) {
        T oldValue = (T) (values == null ? null : values.get(name));
        if (oldValue instanceof Node) {
            Node oldChild = (Node) oldValue;
            oldChild.parent = null;
        }
        if (value instanceof Node) {
            Node child = (Node) value;
            if (!child.getName().equals(name)) {
                throw new IllegalArgumentException("Cannot set a node because the name of the node is not equal to parameter 'name'.");
            }
            child.parent = this;
        }
        if (values == null) {
            values = new HashMap();
        }
        values.put(name, value);
        fireOnSet(this, name, oldValue, value, false);
        return oldValue;
    }

    private String checkName(String name) {
        if (name == null) {
            throw new IllegalArgumentException("Name may not be null.");
        }
        return name;
    }

    private void fireOnName(Node node, String oldName, String newName, boolean bubblePhase) {
        if (listeners != null) {
            for (NodeListener listener : listeners) {
                if (bubblePhase && !(listener instanceof BubbleNodeListener)) {
                    continue;
                }
                listener.onName(node, oldName, newName);
            }
        }
        if (parent != null) {
            parent.fireOnName(node, oldName, newName, true);
        }
    }

    private void fireOnParent(Node node, Node oldParent, Node newParent, boolean bubblePhase) {
        if (listeners != null) {
            for (NodeListener listener : listeners) {
                if (bubblePhase && !(listener instanceof BubbleNodeListener)) {
                    continue;
                }
                listener.onParent(node, oldParent, newParent);
            }
        }
        if (!bubblePhase && oldParent != null) {
            oldParent.fireOnParent(node, oldParent, newParent, true);
        }
        if (parent != null) {
            parent.fireOnParent(node, oldParent, newParent, true);
        }
    }

    private void fireOnSet(Node node, String name, Object oldValue, Object newValue, boolean bubblePhase) {
        if (listeners != null) {
            for (NodeListener listener : listeners) {
                if (bubblePhase && !(listener instanceof BubbleNodeListener)) {
                    continue;
                }
                listener.onSet(node, name, oldValue, newValue);
            }
        }
        if (parent != null) {
            parent.fireOnSet(node, name, oldValue, newValue, true);
        }
    }

    private void fireOnRemove(Node node, String name, Object oldValue, boolean bubblePhase) {
        if (listeners != null) {
            for (NodeListener listener : listeners) {
                if (bubblePhase && !(listener instanceof BubbleNodeListener)) {
                    continue;
                }
                listener.onRemove(node, name, oldValue);
            }
        }
        if (parent != null) {
            parent.fireOnRemove(node, name, oldValue, true);
        }
    }
}
